<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UsersController extends Controller
{
    public function register(Request $request)
    {
        //检查一下参数
        if (!$request->username || !$request->pwd || !$request->email) {
            return $this->errorJson(-1, '参数错误');
        }
        //检查一下 是否重复用户名
        $user = DB::table('user')->where('username', $request->username)->first(); //
        if ($user) {
            return $this->errorJson(-2, '用户名已存在');
        }
        //添加
        $res = DB::table('user')->insert([
            "username" => $request->username,
            'pwd' => md5($request->pwd),
        ]);
        //判断是否添加成功
        if (!$res) {
            return $this->errorJson(-3, '添加失败');
        }
        //成功返回
        return $this->successJson();
    }
    //获取用户列表
    public function getUserList()
    {
        $res = DB::table('user')->orderby("id", "desc")->get();
        return $this->successJson($res);
    }
    //添加用户
    public function addUser(Request $request)
    {
        //检查一下参数
        if (!$request->username || !$request->pwd) {
            return $this->errorJson(-1, '参数错误');
        }
        //检查一下 是否重复用户名
        $user = DB::table('user')->where('username', $request->username)->first(); //
        if ($user) {
            return $this->errorJson(-2, '用户名已存在');
        }
        //添加
        $res = DB::table('user')->insert([
            "username" => $request->username,
            'pwd' => md5($request->pwd),
        ]);
        //判断是否添加成功
        if (!$res) {
            return $this->errorJson(-3, '添加失败');
        }
        //成功返回
        return $this->successJson();
    }
    public function edit(Request $request)
    {
        //检查一下参数
        if (!$request->username || !$request->pwd || !$request->id) {
            return $this->errorJson(-1, '参数错误');
        }
        $affected = DB::table('user')
            ->where('id', $request->id)
            ->update([
                "username" => $request->username,
                'pwd' => md5($request->pwd),
            ]);
        if (!$affected) {
            return $this->errorJson(-1, '更新失败' . $affected);
        }
        return $this->successJson();
    }
    public function del($id)
    {
        if (!$id) {
            return $this->errorJson(-1, '参数错误');
        }
        $deleted = DB::table('user')->where('id', $id)->delete();
        if (!$deleted) {
            return $this->errorJson(-1, '删除失败' . $deleted);
        }
        return $this->successJson();
    }
    //成功返回函数
    public function successJson($data = null)
    {
        if ($data) {
            return json_encode(["code" => 200, 'msg' => 'success', 'data' => $data]);

        } else {
            return json_encode(["code" => 200, 'msg' => 'success']);
        }
    }
    //失败返回函数
    public function errorJson($code, $msg)
    {
        return json_encode(["code" => $code, 'msg' => $msg]);
    }

}
